package com.yupi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.yupi.common.BaseResponse;
import com.yupi.common.ErrorCode;
import com.yupi.common.ResultUtils;
import com.yupi.exception.BusinessException;
import com.yupi.model.domain.Team;
import com.yupi.model.domain.UserTeam;
import com.yupi.model.domain.Userinfo;
import com.yupi.model.dto.*;
import com.yupi.model.vo.TeamVO;
import com.yupi.service.TeamService;
import com.yupi.service.UserTeamService;
import com.yupi.service.UserinfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private UserinfoService userinfoService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 新增队伍
     *
     * @param teamAddDTO
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddDTO teamAddDTO, HttpServletRequest request) {
        if (teamAddDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddDTO, team);
        long result = teamService.addTeam(team, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(long id) {
        if (id < 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "id不能小于0");
        }
        boolean result = teamService.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(result);
    }

    /**
     * 修改
     *
     * @param teamUpdateDTO
     * @return
     */
    @PutMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateDTO teamUpdateDTO, HttpServletRequest request) {
        if (teamUpdateDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateDTO, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改失败");
        }
        return ResultUtils.success(result);
    }

    /**
     * 条件查询
     *
     * @param teamQueryDTO
     * @return
     */
//    @GetMapping("/list")
//    public BaseResponse<List<Team>> listTeam(TeamQueryDTO teamQueryDTO) {
//        if (teamQueryDTO == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Team team = new Team();
//        BeanUtils.copyProperties(teamQueryDTO, team);
//        QueryWrapper<Team> qw = new QueryWrapper<>(team);
//        List<Team> teamList = teamService.list(qw);
//        return ResultUtils.success(teamList);
//    }
    @GetMapping("/list")
    public BaseResponse<List<TeamVO>> listTeam(TeamQueryDTO teamQueryDTO, HttpServletRequest request) {
        if (teamQueryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean isAdmin = userinfoService.isAdmin(request);
        List<TeamVO> teamList = teamService.listTeams(teamQueryDTO, isAdmin);
        //判断当前用户是否加入队伍

        //队伍的id集合
        List<Long> teamIdList = teamList.stream().map(TeamVO::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            Userinfo loginUser = userinfoService.getLoginUser(request);
            userTeamQueryWrapper.eq("user_id", loginUser.getId());
            userTeamQueryWrapper.in("team_id", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
        }

        //todo 关联查询已加入队伍的数量(鱼皮版)
//        QueryWrapper<UserTeam> userJoinTeamQW = new QueryWrapper<>();
//        userJoinTeamQW.in("team_id", teamIdList);
//        List<UserTeam> userJoinTeamList = userTeamService.list(userTeamQueryWrapper);
//        //根据teamid分组
//        Map<Long, List<UserTeam>> userJoinTeamMap = userJoinTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
//        teamList.forEach(team -> {
//            team.setUserVOS();
//        })
        return ResultUtils.success(teamList);
    }

    /**
     * 分页
     *
     * @param teamQueryDTO
     * @return
     */
    @GetMapping("/page")
    public BaseResponse<Page<Team>> pageTeam(TeamQueryDTO teamQueryDTO) {
        if (teamQueryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQueryDTO, team);
        QueryWrapper<Team> qw = new QueryWrapper<>(team);
        Page<Team> pageResult = teamService.page(new Page<>(teamQueryDTO.getPageNum(), teamQueryDTO.getPageSize()), qw);
        return ResultUtils.success(pageResult);
    }

    /**
     * 加入队伍
     *
     * @param teamJoinDTO
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinDTO teamJoinDTO, HttpServletRequest request) {
        if (teamJoinDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        boolean result = teamService.joinTeam(teamJoinDTO, loginUser);

        return ResultUtils.success(result);
    }

    /**
     * 退出队伍
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitDTO teamQuitDTO, HttpServletRequest request) {
        //判空
        if (teamQuitDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        //调用退出队伍方法
        Boolean result = teamService.quitTeam(teamQuitDTO, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 队长解散队伍
     *
     * @param teamQuitDTO
     * @param request
     * @return
     */
    @PostMapping("/dissolve")
    public BaseResponse<Boolean> dissolveTeam(@RequestBody TeamQuitDTO teamQuitDTO, HttpServletRequest request) {
        //判空
        if (teamQuitDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        //调用退出队伍方法
        Boolean result = teamService.dissolveTeam(teamQuitDTO, loginUser);
        return ResultUtils.success(result);
    }

    @GetMapping("/getTeamById")
    public BaseResponse<TeamVO> getTeamById(Long id) {

        if (id == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该队伍不存在");
        }
        return ResultUtils.success(team);
    }

//    @GetMapping("/myTeam")
//    public BaseResponse<List<TeamVO>> getMyTeam(HttpServletRequest request) {
//        Userinfo loginUser = this.userinfoService.getLoginUser(request);
//        if (loginUser == null) {
//            throw new BusinessException(ErrorCode.NOT_LOGIN);
//        }
//        List<Team> userTeamList = this.teamService.getMyTeam(loginUser);
//        List<TeamVO> teamVOList = new ArrayList<>();
//        userTeamList.forEach(team -> {
//            TeamVO teamVO = new TeamVO();
//            BeanUtils.copyProperties(team, teamVO);
//            teamVOList.add(teamVO);
//        });
//        return ResultUtils.success(teamVOList);
//    }

    @GetMapping("/myTeam")
    public BaseResponse<List<TeamVO>> myTeam(TeamQueryDTO teamQueryDTO, HttpServletRequest request) {
        if (teamQueryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Userinfo loginUser = userinfoService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        if (CollectionUtils.isEmpty(userTeamList)) {
            return ResultUtils.success(null);
        }
        //去除不重复的队伍id
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        teamQueryDTO.setIdList(idList);
        List<TeamVO> teamList = teamService.listTeams(teamQueryDTO, true);
        //获取队伍的id集合
        List<Long> teamIdList = teamList.stream().map(TeamVO::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            userTeamQueryWrapper.eq("user_id", loginUser.getId());
            userTeamQueryWrapper.in("team_id", teamIdList);
            List<UserTeam> userTeamJoinList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamJoinList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
        }
        return ResultUtils.success(teamList);
    }

}
